package com.example.houseitemmanagebackend.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.houseitemmanagebackend.entity.Role;
import com.example.houseitemmanagebackend.entity.Users;
import com.example.houseitemmanagebackend.mapper.RoleMapper;
import com.example.houseitemmanagebackend.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义UserDetailsService实现
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        Users users = userMapper.selectOne(new LambdaQueryWrapper<Users>()
                .eq(Users::getUsername, username));

        if (users == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        // 查询用户角色
        List<Role> roles = roleMapper.selectRolesByUserId(users.getId());
        List<GrantedAuthority> authorities = new ArrayList<>();

        // 添加角色
        if (roles != null && !roles.isEmpty()) {
            authorities.addAll(roles.stream()
                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
                    .collect(Collectors.toList()));
        }

        // 查询权限列表（本例中简化处理，实际应该从数据库查询）
        // 这里可以根据角色查询对应的权限，然后添加到authorities中

        return new JwtUserDetails(
                users.getId(),
                users.getUsername(),
                users.getPassword(),
                users.getNickname(),
                users.getEmail(),
                users.getPhone(),
                users.getAvatar(),
                users.getStatus() == 1,
                authorities);
    }
}